<template>
  <view class="admin-scan-page">
    <view class="scan-container">
      <QRScanner title="扫码核销" subtitle="扫描用户订单二维码或点击手动输入订单号进行核销" action-type="process" @scan-success="onScanSuccess"
        @scan-error="onScanError" @order-process="onOrderProcess" @order-detail="onOrderDetail" />
    </view>

    <!-- 处理订单弹窗 -->
    <view v-if="showProcessModal" class="process-modal" @click="closeProcessModal">
      <view class="process-content" @click.stop>
        <view class="process-header">
          <text class="process-title">订单核销</text>
          <text class="process-close" @click="closeProcessModal">×</text>
        </view>

        <view class="process-body">
          <view class="order-summary">
            <view class="summary-item">
              <text class="summary-label">订单号：</text>
              <text class="summary-value">{{ orderNumber }}</text>
            </view>
            <view class="summary-item">
              <text class="summary-label">用户：</text>
              <text class="summary-value">{{ userName }}</text>
            </view>
            <view class="summary-item">
              <text class="summary-label">金额：</text>
              <text class="summary-value amount">¥{{ orderAmount }}</text>
            </view>
            <view class="summary-item">
              <text class="summary-label">当前状态：</text>
              <text class="summary-value status" :class="statusClass">
                {{ statusText }}
              </text>
            </view>
          </view>

          <view class="status-actions">
            <text class="actions-title">选择操作：</text>
            <view class="action-buttons">
              <button v-for="action in availableActions" :key="action.status" class="action-button"
                :class="action.class" @click="updateOrderStatus(action.status)" :disabled="processing">
                <uni-icons :type="action.icon" size="20" :color="action.iconColor"></uni-icons>
                <text>{{ action.text }}</text>
              </button>
            </view>
          </view>

          <view class="notes-section">
            <text class="notes-label">备注（可选）：</text>
            <textarea v-model="adminNotes" class="notes-textarea" placeholder="请输入处理备注..." :maxlength="200" />
          </view>
        </view>

        <view class="process-actions">
          <button class="cancel-btn" @click="closeProcessModal" :disabled="processing">
            取消
          </button>
          <button class="detail-btn" @click="viewOrderDetail" :disabled="processing">
            查看详情
          </button>
        </view>
      </view>
    </view>

    <!-- 处理结果提示 -->
    <view v-if="showResultModal" class="result-modal" @click="closeResultModal">
      <view class="result-content" @click.stop>
        <view class="result-header">
          <uni-icons :type="processResult.success ? 'checkmarkempty' : 'info'" size="48"
            :color="processResult.success ? '#52c41a' : '#ff5722'"></uni-icons>
          <text class="result-title">{{ processResult.success ? '处理成功' : '处理失败' }}</text>
        </view>
        <text class="result-message">{{ processResult.message }}</text>
        <button class="result-btn" @click="closeResultModal">
          {{ processResult.success ? '继续扫描' : '重试' }}
        </button>
      </view>
    </view>

    <!-- 加载遮罩 -->
    <view v-if="processing" class="processing-overlay">
      <uni-load-more status="loading" content-text="处理中..."></uni-load-more>
    </view>
  </view>
</template>

<script>
import QRScanner from '@/components/QRScanner.vue'
import { updateOrderStatus } from '@/api/orders'

export default {
  name: 'AdminScan',
  components: {
    QRScanner
  },
  data() {
    return {
      showProcessModal: false,
      showResultModal: false,
      processing: false,
      currentOrder: null,
      adminNotes: '',
      processResult: {
        success: false,
        message: ''
      }
    }
  },
  computed: {
    // 安全获取订单号
    orderNumber() {
      if (!this.currentOrder || !this.currentOrder.orderNumber) {
        return '未知订单号'
      }
      return this.currentOrder.orderNumber
    },

    // 安全获取用户信息
    userName() {
      if (!this.currentOrder || !this.currentOrder.User) {
        return '未知用户'
      }
      return this.currentOrder.User.nickname || this.currentOrder.User.phone || '未知用户'
    },

    // 安全获取订单金额
    orderAmount() {
      if (!this.currentOrder || !this.currentOrder.finalAmount) {
        return 0
      }
      return this.currentOrder.finalAmount
    },

    // 安全获取订单状态
    orderStatus() {
      if (!this.currentOrder || !this.currentOrder.status) {
        return 'unknown'
      }
      return this.currentOrder.status
    },

    // 获取状态显示文本
    statusText() {
      return this.getStatusText(this.orderStatus)
    },

    // 获取状态样式类
    statusClass() {
      return this.getStatusClass(this.orderStatus)
    },

    // 根据订单状态获取可用操作
    availableActions() {
      if (!this.currentOrder) return []

      const status = this.currentOrder.status
      const actions = []

      switch (status) {
        case 'confirmed':
          actions.push(
            { status: 'processing', text: '开始处理', icon: 'gear', iconColor: '#007aff', class: 'action-processing' },
            { status: 'cancelled', text: '取消订单', icon: 'close', iconColor: '#ff5722', class: 'action-cancel' }
          )
          break
        case 'processing':
          actions.push(
            { status: 'printing', text: '开始打印', icon: 'compose', iconColor: '#9c27b0', class: 'action-printing' },
            { status: 'cancelled', text: '取消订单', icon: 'close', iconColor: '#ff5722', class: 'action-cancel' }
          )
          break
        case 'printing':
          actions.push(
            { status: 'completed', text: '完成订单', icon: 'checkmarkempty', iconColor: '#52c41a', class: 'action-complete' }
          )
          break
        default:
          break
      }

      return actions
    }
  },
  methods: {
    // 扫描成功回调
    onScanSuccess(result) {
      console.log('扫描成功:', result)
      this.currentOrder = result.order
      this.showProcessModal = true
    },

    // 扫描失败回调
    onScanError(error) {
      console.error('扫描失败:', error)
      uni.showToast({
        title: error.message || '扫描失败',
        icon: 'none'
      })
    },

    // 处理订单回调
    onOrderProcess(order) {
      this.currentOrder = order
      this.showProcessModal = true
    },

    // 查看订单详情回调
    onOrderDetail(order) {
      uni.navigateTo({
        url: `/pages/orders/detail?id=${order.id}`
      })
    },

    // 更新订单状态
    async updateOrderStatus(newStatus) {
      if (!this.currentOrder) return

      this.processing = true

      try {
        const response = await updateOrderStatus(this.currentOrder.id, {
          status: newStatus,
          adminNotes: this.adminNotes.trim()
        })

        if (response.success) {
          // 更新当前订单数据
          this.currentOrder = response.data

          this.processResult = {
            success: true,
            message: `订单状态已更新为：${this.getStatusText(newStatus)}`
          }

          this.closeProcessModal()
          this.showResultModal = true

          // 强制刷新计算属性
          this.$forceUpdate()

          // 3秒后自动关闭结果弹窗，准备下一次扫描
          setTimeout(() => {
            if (this.showResultModal && this.processResult.success) {
              this.closeResultModal()
            }
          }, 3000)
        } else {
          throw new Error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('更新订单状态失败:', error)
        let errorMessage = '更新失败，请重试'

        if (error.message.includes('权限不足')) {
          errorMessage = '权限不足，请确认您有管理员权限'
        } else if (error.message.includes('网络')) {
          errorMessage = '网络连接失败，请检查网络后重试'
        } else if (error.message) {
          errorMessage = error.message
        }

        this.processResult = {
          success: false,
          message: errorMessage
        }
        this.showResultModal = true
      } finally {
        this.processing = false
      }
    },

    // 查看订单详情
    viewOrderDetail() {
      if (!this.currentOrder) return

      uni.navigateTo({
        url: `/pages/orders/detail?id=${this.currentOrder.id}`
      })
    },

    // 关闭处理弹窗
    closeProcessModal() {
      this.showProcessModal = false
      // 注意：不要在这里重置currentOrder，因为结果弹窗还需要显示订单信息
      this.adminNotes = ''
    },

    // 关闭结果弹窗
    closeResultModal() {
      const wasSuccess = this.processResult.success

      // 重置所有状态
      this.resetScanState()

      // 如果处理成功，提示用户可以继续扫描
      if (wasSuccess) {
        uni.showToast({
          title: '处理完成，可以扫描下一个订单',
          icon: 'success',
          duration: 2000
        })
      }
    },

    // 重置扫描状态
    resetScanState() {
      this.showProcessModal = false
      this.showResultModal = false
      this.processing = false
      this.currentOrder = null
      this.adminNotes = ''
      this.processResult = {
        success: false,
        message: ''
      }
    },

    // 获取状态文本
    getStatusText(status) {
      if (!status) return '未知状态'

      const statusMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'processing': '处理中',
        'printing': '打印中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知状态'
    },

    // 获取状态样式
    getStatusClass(status) {
      if (!status) return 'status-unknown'
      return `status-${status}`
    }
  }
}
</script>

<style lang="scss" scoped>
.admin-scan-page {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  padding: 40rpx 30rpx 20rpx;
  background: #fff;
  text-align: center;

  .page-title {
    display: block;
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .page-subtitle {
    display: block;
    font-size: 28rpx;
    color: #666;
  }
}

.scan-container {
  flex: 1;
}

.process-modal,
.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.process-content,
.result-content {
  background: #fff;
  border-radius: 16rpx;
  margin: 40rpx;
  max-width: 700rpx;
  width: 100%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.process-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .process-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .process-close {
    font-size: 48rpx;
    color: #999;
    line-height: 1;
    padding: 10rpx;
  }
}

.process-body {
  flex: 1;
  padding: 30rpx;
  overflow-y: auto;
}

.order-summary {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;

  .summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .summary-label {
      font-size: 28rpx;
      color: #666;
    }

    .summary-value {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;

      &.amount {
        color: #ff5722;
        font-size: 32rpx;
      }

      &.status {
        &.status-pending {
          color: #ff9800;
        }

        &.status-confirmed {
          color: #2196f3;
        }

        &.status-processing {
          color: #9c27b0;
        }

        &.status-printing {
          color: #ff5722;
        }

        &.status-completed {
          color: #4caf50;
        }

        &.status-cancelled {
          color: #f44336;
        }

        &.status-unknown {
          color: #999;
        }
      }
    }
  }
}

.status-actions {
  margin-bottom: 30rpx;

  .actions-title {
    display: block;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .action-buttons {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
  }

  .action-button {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    height: 80rpx;
    border-radius: 8rpx;
    font-size: 32rpx;
    border: none;

    &.action-processing {
      background: #e3f2fd;
      color: #1976d2;
    }

    &.action-printing {
      background: #f3e5f5;
      color: #7b1fa2;
    }

    &.action-complete {
      background: #e8f5e8;
      color: #388e3c;
    }

    &.action-cancel {
      background: #ffebee;
      color: #d32f2f;
    }

    &:disabled {
      opacity: 0.6;
    }
  }
}

.notes-section {
  .notes-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
  }

  .notes-textarea {
    width: 100%;
    min-height: 120rpx;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 8rpx;
    font-size: 28rpx;
    line-height: 1.4;
    resize: none;

    &:focus {
      border-color: #007aff;
    }
  }
}

.process-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;

  .cancel-btn,
  .detail-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 8rpx;
    font-size: 32rpx;
    border: none;
  }

  .cancel-btn {
    background: #f0f0f0;
    color: #333;
  }

  .detail-btn {
    background: #007aff;
    color: #fff;
  }

  .cancel-btn:disabled,
  .detail-btn:disabled {
    opacity: 0.6;
  }
}

.result-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 30rpx 20rpx;

  .result-title {
    font-size: 36rpx;
    font-weight: bold;
    margin-top: 20rpx;
  }
}

.result-message {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  line-height: 1.4;
  padding: 0 30rpx 30rpx;
}

.result-btn {
  margin: 0 30rpx 30rpx;
  height: 80rpx;
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
}

.processing-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
}
</style>